#!/usr/bin/env node

const https = require('https'),
      url  = require('url'),
      cheerio = require('cheerio'),
      fs = require('fs'),
      addr = 'https://maoyan.com/films?showType=3';

let opt = url.parse(addr);
opt.headers = {
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36 Edg/86.0.622.58',
  'cookie': '__mta=188502935.1604020120157.1604020120157.1604023041104.2; uuid_n_v=v1; uuid=6D3D69701A4C11EBA61D33BF8F97C8ECFA4EBEC5F6364FDA8C8197CC3A9D6F87; _lxsdk_cuid=175770ca3c9c8-0659b19321b609-7d677f69-144000-175770ca3c9c8; _lxsdk=6D3D69701A4C11EBA61D33BF8F97C8ECFA4EBEC5F6364FDA8C8197CC3A9D6F87; _csrf=aec87cbb24c3fe41114131f91a842fa082f892d2e22da446f94c93c161d30476; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1604020116,1604301254,1604386110,1604387936; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1604387936; __mta=188502935.1604020120157.1604023041104.1604387936426.3; _lxsdk_s=1758cdd3cdc-b09-8d-53f%7C%7C4',
  'Sec-Fetch-Mode': 'navigate',
  'Sec-Fetch-Site': 'none',
  'Sec-Fetch-User': '?1'
};

https.get(opt, (res)=>{
  let data = '';
  let movieList = [];
  res.on('data', (chunk) => data += chunk);
  res.on('end', ()=>{
    let $ = cheerio.load(data);
    let nameid = $('body').find('.channel-detail>a');
    let range = $('body').find('.movie-item-title~.channel-detail-orange');
    for(let i=0; i<nameid.length; i++){
      let movie = {
        movieId:$(nameid[i]).attr('data-val').split(':')[1].split('}')[0], 
        movieName:$(nameid[i]).text(), 
        movieRange:$(range[i]).text()
      };
      movieList[i] = movie;
    }
    try{
      fs.writeFileSync('./movieData.json', JSON.stringify(movieList));
    }catch(e){
      console.error(e.message);
    }
  });
});

